

import 'package:erp/Entity/ProductDetailAtPurchaseOrSell.dart';
import 'package:erp/Entity/ProductInWareHouse.dart';
import 'package:erp/Entity/WareHouse.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/ProductsInWareHouseStore.dart';
import 'package:erp/Store/WareHouse.dart';
import 'package:erp/UI/CodeResources/Localization.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/KeyValueView.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';

class WareHouseManagementPage extends StatefulWidget {
  bool isSelectionMode;
  String title;

  WareHouseManagementPage({this.isSelectionMode = false, this.title});

  @override
  State<StatefulWidget> createState() => WareHouseManagementPageState();
}

typedef void Action();

class WareHouseManagementPageState  extends EventfulState<WareHouseManagementPage> {

  WareHouse selectedWareHouse;
  WareHouseManagementPageState(){
    selectedWareHouse = WareHouseStore.wareHouses.firstWhere((item) => true, orElse: () => null);
  }

  List<Widget> items = [];

  @override
  void initState() {
    eventIds = [
      globalBus.subscribe<List<ProductInWareHouse>>(Events.PRODUCT_IN_WAREHOUSE_SELECT_SUCCESS, (bus, data){
        search("");
        setState(() {});
      }),
      globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_EDIT_SUCCESS, (bus, data){
        search("");
        setState((){});
      }),
      globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_EDIT_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "ئىدىتلاش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe<ProductInWareHouse>(Events.PRODUCT_IN_WAREHOUSE_EDIT_SUCCESS, (bus, data) {
        search("");
        setState(() {});
      }),
      globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_DELETE_SUCCESS, (bus, data){
        search("");
        setState((){});
      }),
      globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_DELETE_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_ERROR, (bus, error) async {
        await showMessageDialog(context, title: "باھا تەڭشەش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe<ProductInWareHouse>(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_SUCCESS, (bus, data) {
        search("");
        setState(() {});
      }),
    ];
    super.initState();

    search("");
  }

  void search(String text){
    items = ProductsInWareHouseStore.products.where((product) => (
        selectedWareHouse?.id ?? -1) == product.warehouse
        && (
            product.nameUg.contains(text)
            || product.code.contains(text)
            || product.barCode.contains(text)
        )
    ).map((product) => buildProductItem(product)).toList();

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
      title: widget.title ?? "ئامبار باشقۇرۇش",
      pinned: true,
      assetsLogoName: "assets/pictures/warehause.png",
      heroName: "WareHouseHero",
      useSearchBar: true,
      searchHandler: search,
      endDrawer: Container(
        padding: EdgeInsets.symmetric(vertical: 20.0),
        width: 110.0,
        color: Colors.white,
        child: ListView(
          children: ListDividerGenerator(WareHouseStore.wareHouses.map((wareHouse) => buildWareHouseListItem(wareHouse)).toList(), Divider()).items
        )
      ),
      contentDelegate: SliverChildListDelegate(items),
      backgroundColor: Color(0xffdddddd),
    );
  }

  Widget buildProductItem(ProductInWareHouse product){
//    print("WareHouseManagementPage-BuildProductItem");
    var parseResult = parseAttach(product.attach);
    var layout = Container(
      height: 160.0,
      padding: EdgeInsets.symmetric(vertical: 3.0),
      child: Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(right: 10.0 + 57.0, left: 20.0, top: 7.0, bottom: 7.0),
            constraints: BoxConstraints.expand(),
            decoration: BoxDecoration(
              color: Color(0xffe5e5e5),
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(8),
                bottomLeft: Radius.circular(8),
                topRight: Radius.circular(14),
                bottomRight: Radius.circular(14),
              ),
              boxShadow: [
                BoxShadow(color: Colors.black12, offset: Offset(0.0, 5.0), blurRadius: 5.0, spreadRadius: 5.0)
              ]
            ),
            child: Padding(
              padding: EdgeInsets.only(right: 57 + 10.0, top: 5.0, bottom: 5.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Expanded(child: KeyValueView({
                    "ئىسمى: ": product.nameUg,
                    "قالدۇق سانى: ": product.balanceCount,
                    "كىرىش باھاسى: ": parseResult.inPrice,
                    "سىتىش باھاسى: ": parseResult.sellPrice,
                    "تاياقچە كودى: ": product.barCode,
                    "نومۇرى: ": product.code,
                  })),
                  Column(
                    children: <Widget>[
                      Container(
                        width: 40.0,
                        height: 40.0,
                        child: PopupMenuButton<Action>(
                          onSelected: (action){
                            action();
                          },
                          itemBuilder: (context) => <PopupMenuEntry<Action>>[
                            PopupMenuItem<Action>(
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.repeat),
                                  Text("ئىدىتلاش"),
                                ],
                              ),
                              value: () async {
                                var clonedProduct = ProductInWareHouse.fromJson(product.toJson());
                                var result = await showEditDialog(context, clonedProduct) ?? false;
                                if (result){
                                  globalBus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_REQUEST, clonedProduct);
                                }
                              },
                            ),
                            PopupMenuItem<Action>(
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.attach_money),
                                  Text("باھا تەڭشەش"),
                                ],
                              ),
                              value: () async {
                                var clonedProduct = ProductInWareHouse.fromJson(product.toJson());
                                var result = await showPriceEditDialog(context, clonedProduct) ?? false;
                                if (result) globalBus.publish(Events.PRODUCT_IN_WAREHOUSE_EDIT_PRICE_REQUEST, clonedProduct);
                              },
                            ),
                            PopupMenuItem<Action>(
                              child: Row(
                                children: <Widget>[
                                  Icon(Icons.delete_forever),
                                  Text("ئۆچۈرۈش"),
                                ],
                              ),
                              value: () async {
                                var result = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "راستىنلا ئۆچۈرەمسىز؟") ?? false;
                                if (!result) return;
                                globalBus.publish(Events.PRODUCT_IN_WAREHOUSE_DELETE_REQUEST, product);
                              },
                            ),
                          ],
                        )
                      )
                    ],
                  ),
                ],
              )
            ),
          ),
          Container(
            alignment: Alignment(1.0, 0.0),
            padding: EdgeInsets.only(right: 10.0),
            child: CircleAvatar(
              radius: 57,
              backgroundColor: Color(0xffffffff),
              backgroundImage: product.imgUrl != null? NetworkImage(product.imgUrl) : null,
            ),
          )
        ],
      ),
    );

    return GestureDetector(
      child: layout,
      onTap: (){
        if (widget.isSelectionMode) Navigator.of(context).pop(product);
      },
    );
  }

  Widget buildWareHouseListItem(WareHouse wareHouse) {
    return SizedBox(
      height: 100.0,
      child: Row(
        children: <Widget>[
          Container(
            width: 3.0,
            color: (selectedWareHouse?.id ?? -1) == wareHouse.id ? Colors.blue : Colors.transparent,
          ),
          Expanded(
            child: FlatButton(
              child: Column(
                children: <Widget>[
                  Expanded(
                      child: Center(
                        child: CircleAvatar(
                          backgroundColor: Colors.blue,
                          radius: 30.0,
                        )
                      )
                  ),
                  Text(wareHouse.name, textAlign: TextAlign.center, style: TextStyle(),)
                ],
              ),
              onPressed: (){
                setState(() {
                  selectedWareHouse = wareHouse;
                  search("");
                });
                Navigator.of(context).pop();
              },
            ),
          ),
        ],
      )
    );
  }

  Future<bool> showEditDialog(BuildContext context, ProductInWareHouse product) async {
    var currentLocale = AppLocalizations.of(context);
    var balanceCount = 0.0;
    var comment = "";

    return await showDialog(context: context, barrierDismissible: false, builder: (context) => Directionality(textDirection: currentLocale.textDirection, child: AlertDialog(
      title: Text("ئىدىتلاش"),
      content: Wrap(
        children: <Widget>[
          Text("نۆۋەتتىكى ئامباردىكى سانى: ${product.balanceCount} ${product.unit}"),
          TextField(
            decoration: InputDecoration(
              labelText: "ئەمەلىي سانى",
              hintText: "ئەمەلىي سانىنى كىرگۈزۈڭ",
              prefixIcon: Icon(Icons.confirmation_number),
              suffix: Text(product.unit)
            ),
            onChanged: (text) {
              try {
                balanceCount = double.parse(text);
              }
              catch (_){
                balanceCount = 0;
              }
            },
            keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
          ),
          TextField(
            decoration: InputDecoration(
              labelText: "ئىزاھات",
              hintText: "ئىزاھاتىنى يىزىشىڭىز زۆرۈر",
            ),
            onChanged: (text) => comment = text,
            maxLines: 2,
          ),
        ],
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("جەزىملەشتۈرۈش"),
          onPressed: () async {
            if (balanceCount == null || balanceCount == 0.0){
              await showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەمەلىي سانىنى كىرگۈزۈڭ");
              return;
            }
            if (comment.isEmpty || comment.length < 11){
              await showMessageDialog(context, title: "ئەەسكەرتىش", content: "ئىزاھات يىزىشىڭىز زۆرۈر");
              return;
            }
            product.balanceCount = balanceCount;
            product.comment = comment;

            Navigator.of(context).pop(true);
          },
        ),
        FlatButton(
          child: Text("بىكار قىلىش"),
          onPressed: () {
            Navigator.of(context).pop(false);
          },
        ),
      ],
    )));
  }

  Future<bool> showPriceEditDialog(BuildContext context, ProductInWareHouse product) async {
    var currentLocale = AppLocalizations.of(context);
    var price = 0.0;
    var comment = "";

    return await showDialog(context: context, barrierDismissible: false, builder: (context) => Directionality(textDirection: currentLocale.textDirection, child: AlertDialog(
      title: Text("باھا تەڭشەش"),
      content: Wrap(
        children: <Widget>[
          Text("نۆۋەتتىكى باھاسى: ${parseAttach(product.attach).sellPrice}"),
          TextField(
            decoration: InputDecoration(
                labelText: "ئەمەلىي باھاسى",
                hintText: "ئەمەلىي باھاسىنى كىرگۈزۈڭ",
                prefixIcon: Icon(Icons.confirmation_number),
                suffix: Text(product.unit)
            ),
            onChanged: (text) {
              try {
                price = double.parse(text);
              }
              catch (_){
                price = 0;
              }
            },
            keyboardType: TextInputType.numberWithOptions(signed: true, decimal: true),
          ),
          TextField(
            decoration: InputDecoration(
              labelText: "ئىزاھات",
              hintText: "ئىزاھاتىنى يىزىشىڭىز زۆرۈر",
            ),
            onChanged: (text) => comment = text,
            maxLines: 2,
          ),
        ],
      ),
      actions: <Widget>[
        FlatButton(
          child: Text("جەزىملەشتۈرۈش"),
          onPressed: () async {
            if (price == null || price == 0.0){
              await showMessageDialog(context, title: "ئەسكەرتىش", content: "ئەمەلىي باھانى كىرگۈزۈڭ");
              return;
            }
            if (comment.isEmpty || comment.length < 11){
              await showMessageDialog(context, title: "ئەەسكەرتىش", content: "ئىزاھات يىزىشىڭىز زۆرۈر");
              return;
            }
            product.sellPrice = price;
            product.comment = comment;

            Navigator.of(context).pop(true);
          },
        ),
        FlatButton(
          child: Text("بىكار قىلىش"),
          onPressed: () {
            Navigator.of(context).pop(false);
          },
        ),
      ],
    )));
  }
}

